package com.mida.app.knw.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mida.app.knw.enumData.UploadFileTitleEnum;
import com.mida.app.knw.service.KnwCompositeInstanceService;
import com.mida.app.knw.service.MdmService;
import com.mida.app.knw.service.SoidService;
import com.mida.app.knw.vo.EmployeeInfoTmpVo;
import com.mida.dms.knw.api.KnwCompositeInstanceApi;
import com.mida.dms.knw.entity.KnwCommonWordsTree;
import com.mida.dms.knw.entity.KnwCompositeInstance;
import com.mida.dms.knw.entity.KnwCompositeInstanceShortcut;
import com.mida.dms.knw.entity.KnwNarrativeBlock;
import com.mida.dms.knw.entity.vo.KnwCompositeInstanceDto;
import com.mida.dms.knw.vo.KnwCompositeInstanceExcelVo;
import com.mida.dms.knw.vo.KnwCompositeInstanceVo;
import com.mida.dms.knw.vo.KnwCompositeTmpVo;
import com.mida.dms.knw.vo.PageResultVo;
import com.mida.dms.mdm.api.provider.IBusinessUnitApi;
import com.mida.dms.mdm.api.provider.IEmployeeInfoApi;
import com.mida.dms.mdm.api.provider.IOrgInfoApi;
import com.mida.dms.mdm.dto.UserDto;
import com.mida.dms.mdm.vo.provider.BaseOrgInfoVo;
import com.mida.dms.mdm.vo.provider.BusinessUnitVo;
import com.mida.dms.mdm.vo.provider.EmployeeInfoVo;
import com.mida.tool.common.result.ActionResult;
import com.mida.tool.common.result.BaseResult;
import com.mida.tool.common.result.ListResult;
import com.mida.tool.common.utils.CharTransFormUtil;
import com.mida.tool.common.utils.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * KnwCompositeInstanceService
 */
@Slf4j
@Service
@Transactional
public class KnwCompositeInstanceServiceImpl extends BaseResult implements KnwCompositeInstanceService {

    private static final long SHORTCUT_TYPE = 35076626068799488L;
    private static final long STATUS = 149L;
    private static final long IS_DELETE = 0l;
    private static final String XLSX = "xlsx";
    private static final String ERROR_MESSAGE_001 = "文件不存在";
    private static final String ERROR_MESSAGE_002 = "文件扩展名不正确";
    private static final String ERROR_MESSAGE_003 = "当前登录用户医院标识为空";
    private static final String ERROR_MESSAGE_004 = "根据当前上传模板中的用户HIS_ID和登录医院ID，查询数据库用户信息不存在";
    private static final String ERROR_MESSAGE_005 = "当前登录用户和上传用户不一致";

    private static final String DOT = ".";
    private static final String CELL = "单元格的";
    private static final String IS_NULL = "为空";
    private static final String REPETITION = "重复";
    private static final String UNDER_LINE = "_";

    /**
     * 复合实例Mapper
     */
    @Autowired
    private KnwCompositeInstanceApi knwCompositeInstanceApi;

    @Autowired
    private IEmployeeInfoApi employeeInfoApi;

    @Autowired
    private IBusinessUnitApi businessUnitApi;

    @Autowired
    private IOrgInfoApi orgInfoApi;

    @Autowired
    private MdmService mdmService;

    /**
     * soidService
     */
    @Autowired
    private SoidService soidService;

    @Value("file:config/wordTemplate.xlsx")
    private File fileTmp;


    Map<String, EmployeeInfoTmpVo> mapEmployeeInfoVo = new HashMap<>();

    /**
     * 保存复合实例
     *
     * @param knwCompositeInstanceVo
     * @throws Exception
     */
    @Override
    public ActionResult add(KnwCompositeInstanceVo knwCompositeInstanceVo) {
        ActionResult actionResult = new ActionResult();
        try {
            actionResult = knwCompositeInstanceApi.addKnwCompositeInstance(knwCompositeInstanceVo);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            actionResult.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            actionResult.setMessage("保存复合实例处理失败");
            return actionResult;
        }

        return actionResult;
    }

    /**
     * 更新复合实例
     *
     * @param knwCompositeInstanceVo
     * @throws Exception
     */
    @Override
    public ActionResult update(KnwCompositeInstanceVo knwCompositeInstanceVo) {
        ActionResult actionResult = new ActionResult();
        try {
            actionResult = knwCompositeInstanceApi.updateKnwCompositeInstance(knwCompositeInstanceVo);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            actionResult.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            actionResult.setMessage("更新复合实例处理失败");
            return actionResult;
        }

        return actionResult;
    }

    /**
     * 删除复合实例
     *
     * @param knwCompositeInstanceVo
     * @throws Exception
     */
    @Override
    public ActionResult delete(KnwCompositeInstanceVo knwCompositeInstanceVo) {
        return knwCompositeInstanceApi.deleteKnwCompositeInstance(knwCompositeInstanceVo);
    }

    /**
     * 分页查询
     *
     * @param vo
     * @return
     */
    @Override
    public ListResult<PageResultVo<KnwCompositeInstanceVo>> getKnwCompositeInstancePage(KnwCompositeInstanceVo vo) {
        ListResult<PageResultVo<KnwCompositeInstanceDto>> resultTmp = knwCompositeInstanceApi.getKnwCompositeInstancePage(vo);
        ListResult<PageResultVo<KnwCompositeInstanceVo>> result = new ListResult<PageResultVo<KnwCompositeInstanceVo>>();
        if (resultTmp != null && resultTmp.getData() != null) {
            PageResultVo<KnwCompositeInstanceDto> pageResultVoTmp = resultTmp.getData();
            PageResultVo<KnwCompositeInstanceVo> pageResultVo = new PageResultVo<KnwCompositeInstanceVo>();
            List<KnwCompositeInstanceDto> list = pageResultVoTmp.getList();
            List<KnwCompositeInstanceVo> listTmp = new ArrayList<KnwCompositeInstanceVo>();

            if (pageResultVoTmp.getList() == null) {
                result.setData(pageResultVo);
                result.setMessage(resultTmp.getMessage());
                result.setStatus(resultTmp.getStatus());
                return result;
            }

            for (KnwCompositeInstance voTmp :list) {
                KnwCompositeInstanceVo kvo = new KnwCompositeInstanceVo();
                BeanUtils.copyProperties(voTmp, kvo);
                listTmp.add(kvo);
            }

            for (KnwCompositeInstanceVo v:listTmp) {
                if (StringUtils.isNotEmpty(v.getNarrativeBlockContent())) {
                    Map mapType = JSON.parseObject(v.getNarrativeBlockContent(),Map.class);
                    if (mapType != null) {
                        if (mapType.get("usContent") != null) {
                            v.setUsContent(mapType.get("usContent").toString());
                        }
                        if (mapType.get("usDiagnosis") != null) {
                            v.setUsDiagnosis(mapType.get("usDiagnosis").toString());
                        }
                    }
                }
            }
            pageResultVo.setPage(pageResultVoTmp.getPage());
            pageResultVo.setList(listTmp);
            result.setData(pageResultVo);
            result.setMessage(resultTmp.getMessage());
            result.setStatus(resultTmp.getStatus());
        }

        return result;
    }

    /**
     * 值集批量上传处理
     *
     * @param file
     * @return
     */
    @Override
    public ActionResult uploadFile(MultipartFile file) throws Exception {

        ActionResult actionResult = new ActionResult();
        BufferedInputStream bufferedInput = null;
        JSONArray jsonArray = null;

        if (file.isEmpty()) {
            log.error(ERROR_MESSAGE_001);
            actionResult.setMessage(ERROR_MESSAGE_001);
            actionResult.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return actionResult;
        }

        String fileName = file.getOriginalFilename();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(fileName)
                && !XLSX.equals(fileName.substring(fileName.indexOf(DOT) + 1))) {
            log.error(ERROR_MESSAGE_002);
            actionResult.setMessage(ERROR_MESSAGE_002);
            actionResult.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return actionResult;
        }

        bufferedInput = new BufferedInputStream(file.getInputStream());
        Map<String, Object> map = new HashMap();
        List<KnwCompositeInstanceExcelVo> list = new ArrayList<KnwCompositeInstanceExcelVo>();
        if (bufferedInput != null) {
            jsonArray = ExcelUtil.getValues(bufferedInput);
            if (jsonArray != null && jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    map = (Map) jsonArray.get(i);
                    KnwCompositeInstanceExcelVo dataSet;
                    if (map != null && map.size() > 0) {
                        dataSet = new KnwCompositeInstanceExcelVo(map);
                        list.add(dataSet);
                    }
                }
            }
        }

        // 数据校验
        if (list.size() > 0) {
            String errorMsg = checkData(list);
            if (StringUtils.isNotEmpty(errorMsg)) {
                actionResult.setMessage(errorMsg);
                actionResult.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                return actionResult;
            }

            // 批量追加
            actionResult = addKnwComposite(list);

        }

        // 返回
        return actionResult;
    }

    /**
     * 常用语模板下载处理
     *
     * @param res
     * @return
     * @throws Exception
     */
    @Override
    public ActionResult downloadFile(HttpServletResponse res) {

        ActionResult actionResult = new ActionResult();
        ListResult<UserDto> userDto = mdmService.getLoginUserInfo();
        Long userid = null;
        if (userDto != null && userDto.getData() != null) {
            UserDto u = userDto.getData();
            userid = u.getEmployeeSoid();
        } else {
            actionResult.setMessage(ERROR_MESSAGE_003);
            actionResult.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            return actionResult;
        }

        ListResult<EmployeeInfoVo> employeeInfoVo = employeeInfoApi.findOneBySoid(userid, false);
        String hisId = "";
        if (employeeInfoVo != null && employeeInfoVo.getData() != null) {
            EmployeeInfoVo eiVo = employeeInfoVo.getData();
            hisId = eiVo.getHisOid();
        }

        ActionResult result = new ActionResult();
        String realFileName="wordTemplate.xlsx";
        BufferedInputStream bis = null;
        OutputStream os = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            File excelFile = getFileTmp();
            if (!excelFile.exists()) {
                result.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                result.setMessage("模板不存在");
                return result;
            }
            if (StringUtils.isNotEmpty(excelFile.getName())) {
                realFileName = excelFile.getName();
            }

            XSSFWorkbook xSSFWorkbook = null;
            XSSFSheet xSSFSheet = null;
            is = new FileInputStream(excelFile);
            xSSFWorkbook = new XSSFWorkbook(is);
            //获取第一个sheet
            xSSFSheet = xSSFWorkbook.getSheetAt(0);

            if (xSSFSheet != null) {
                //写数据
                fos = new FileOutputStream(excelFile);
                //构建每行的数据内容
                //输出行数据
                Row row = xSSFSheet.createRow(1);
                int cellNum = 5;
                Cell cell;
                // 序号
                cell = row.createCell(cellNum);

                if (hisId != null) {
                    cell.setCellValue(hisId);
                }

                xSSFWorkbook.write(fos);
                fos.flush();
                fos.close();
            }

            res.reset();
            res.setCharacterEncoding("utf-8");
            res.setHeader("content-type", "application/octet-stream;charset=UTF-8");
            //res.setContentType("application/octet-stream;charset=UTF-8");
            res.setContentType("application/ms-excel");
            String newName = URLEncoder.encode(realFileName, "UTF-8");
            res.setHeader("Content-Disposition", "attachment;filename=" + newName);
            res.addHeader("Content-Length", String.valueOf(excelFile.length()));

            byte[] buff = new byte[1024];
            os = res.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(excelFile));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (Exception e) {
            log.error("文件下载处理发生异常:" + e.getMessage(), e);
            result.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            result.setMessage("文件下载处理失败");
            return result;
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    log.error("文件下载处理发生异常:" + e.getMessage(), e);
                    result.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                    result.setMessage("文件下载处理失败");
                    return result;
                }
            }
        }
        buildActionSuccess(result);
        return result;
    }

    /**
     * 设置复合数据
     *
     * @param vo
     */
    private KnwCompositeInstance setKnwCompositeInstance(
            KnwCompositeInstanceVo vo) throws Exception {
        KnwCompositeInstance knwCompositeInstance = new KnwCompositeInstance();
        BeanUtils.copyProperties(vo, knwCompositeInstance);
        if (StringUtils.isNotEmpty(knwCompositeInstance.getCompositeInstanceName())) {
            knwCompositeInstance.setPyCode(
                    CharTransFormUtil.toPinyinSimple(knwCompositeInstance.getCompositeInstanceName()));
            knwCompositeInstance.setWbCode(
                    CharTransFormUtil.toWubi(knwCompositeInstance.getCompositeInstanceName()));
        }
        //knwCompositeInstance.setCreator(vo.getEmployeeSoid());
        knwCompositeInstance.setIsDelete(IS_DELETE);
        return knwCompositeInstance;
    }




    /**
     * 设置复合数据数据
     *
     * @param vo
     */
    private KnwCompositeInstanceShortcut setKnwCompositeInstanceShortcut(
            KnwCompositeInstanceVo vo) throws Exception {
        KnwCompositeInstanceShortcut knwCompositeInstanceShortcut = new KnwCompositeInstanceShortcut();
        if (StringUtils.isNotEmpty(vo.getCompositeInstanceName())) {
            knwCompositeInstanceShortcut.setShortcut(
                    CharTransFormUtil.toPinyinSimple(vo.getCompositeInstanceName()));
            knwCompositeInstanceShortcut.setShortcutType(SHORTCUT_TYPE);
        }
        knwCompositeInstanceShortcut.setCreator(vo.getCreator());
        knwCompositeInstanceShortcut.setStatus(STATUS);
        knwCompositeInstanceShortcut.setIsDelete(IS_DELETE);
        return knwCompositeInstanceShortcut;
    }

    /**
     * 数据校验
     *
     * @param list
     * @return
     */
    private String checkData(List<KnwCompositeInstanceExcelVo> list) throws Exception {
        String errorMsg = "";
        Map<String, String> mapRoot= new HashMap<String, String>();

        ListResult<UserDto> userDto = mdmService.getLoginUserInfo();
        Long hospitalSoid = null;
        Long userid = null;
        if (userDto != null && userDto.getData() != null) {
            UserDto u = userDto.getData();
            hospitalSoid = u.getHospitalSoid();
            userid = u.getEmployeeSoid();
        } else {
            return ERROR_MESSAGE_003;
        }

        mapEmployeeInfoVo = new HashMap<>();
        EmployeeInfoTmpVo evo = new EmployeeInfoTmpVo();
        for (KnwCompositeInstanceExcelVo vo : list) {
            if (StringUtils.isNotEmpty(vo.getUserId())) {
                if (mapEmployeeInfoVo.get(vo.getUserId()) == null) {
                    ListResult<EmployeeInfoVo> result = employeeInfoApi.findOneByHisOid(vo.getUserId(), hospitalSoid);

                    if (result != null
                            && result.getData() != null
                            && result.getData().getEmployeeSoid() != null) {
                        EmployeeInfoVo v = result.getData();
                        if (userid != v.getEmployeeSoid().longValue()) {
                            return ERROR_MESSAGE_005;
                        }

                        evo.setEmployeeSoid(v.getEmployeeSoid());

                        ListResult<List<BusinessUnitVo>> buTmp =
                                businessUnitApi.findBusinessUnitListByEmployeeSoid(
                                        v.getEmployeeSoid(), null);
                        if (buTmp != null && buTmp.getData() != null) {
                            List<BusinessUnitVo> bv = buTmp.getData();
                            if (bv != null && bv.size() > 0) {
                                evo.setBusinessUnitSoid(bv.get(0).getBusinessUnitSoid());
                            }
                        }

                        ListResult<List<BaseOrgInfoVo>> boTmp =
                                orgInfoApi.findHospitalByEmployeeSoid(v.getEmployeeSoid());

                        if (boTmp != null && boTmp.getData() != null) {
                            List<BaseOrgInfoVo> bov = boTmp.getData();
                            if (bov != null && bov.size() > 0) {
                                evo.setOrgInfoSoid(bov.get(0).getOrgInfoSoid());
                            }
                        }

                        mapEmployeeInfoVo.put(vo.getUserId(), evo);
                    } else {
                        return ERROR_MESSAGE_004;
                    }
                }
            }
        }

        for (int i = 0; i < list.size(); i++) {
            KnwCompositeInstanceExcelVo vo = list.get(i);

            // 树型分类名称为空
            if (StringUtils.isEmpty(vo.getCommonWordsTreeName())) {
                errorMsg = UploadFileTitleEnum.COMMON_WORDS_TREE_NAME.getPosition()
                        + (i + 2) + CELL + UploadFileTitleEnum.COMMON_WORDS_TREE_NAME.getName() + IS_NULL;
                return errorMsg;
            }

            if (mapRoot.get(vo.getCommonWordsTreeName() + "_" + vo.getUserId()) == null &&
                    StringUtils.isEmpty(vo.getSurperCommonWordsTreeName())) {
                mapRoot.put(vo.getCommonWordsTreeName() + "_" + vo.getUserId(), "");
            } else if (mapRoot.get(vo.getCommonWordsTreeName() + "_" + vo.getUserId()) != null
                    && StringUtils.isEmpty(vo.getSurperCommonWordsTreeName())) {
                errorMsg = UploadFileTitleEnum.COMMON_WORDS_TREE_NAME.getPosition()
                        + (i + 2) + CELL + UploadFileTitleEnum.COMMON_WORDS_TREE_NAME.getName() + REPETITION;
                return errorMsg;
            }
        }

        return errorMsg;
    }

    /**
     * addKnwComposite
     * @param list
     * @return
     */
    private ActionResult addKnwComposite(List<KnwCompositeInstanceExcelVo> list) {
        ActionResult result = new ActionResult();
        KnwCompositeTmpVo vo = new KnwCompositeTmpVo();

        List<KnwCommonWordsTree> listKnwCommonWordsTree =
                new ArrayList<KnwCommonWordsTree>();
        KnwCommonWordsTree kct = new KnwCommonWordsTree();

        List<KnwCompositeInstance> listKnwCompositeInstance =
                new ArrayList<KnwCompositeInstance>();
        KnwCompositeInstance kci = new KnwCompositeInstance();

        List<KnwCompositeInstanceShortcut> listKnwCompositeInstanceShortcut =
                new ArrayList<KnwCompositeInstanceShortcut>();
        KnwCompositeInstanceShortcut kcis = new KnwCompositeInstanceShortcut();

        List<KnwNarrativeBlock> listKnwNarrativeBlock =
                new ArrayList<KnwNarrativeBlock>();
        KnwNarrativeBlock knb = new KnwNarrativeBlock();

        //soid
        Map<String, Long> mapSoid = new HashMap<String, Long>();

        for (KnwCompositeInstanceExcelVo v : list) {
            Long soid;

            if (StringUtils.isEmpty(v.getSurperCommonWordsTreeName())) {
                mapSoid = new HashMap<String, Long>();
                soid = soidService.getSoid();
                mapSoid.put(v.getCommonWordsTreeName() + UNDER_LINE +
                            v.getUserId(), soid);
                kct = new KnwCommonWordsTree();
                kct = setKnwCommonWordsTree(v, soid, 0l);
                listKnwCommonWordsTree.add(kct);
            } else {

                if (mapSoid.get(v.getCommonWordsTreeName() + UNDER_LINE +
                        v.getUserId()) == null) {
                    soid = soidService.getSoid();
                    mapSoid.put(v.getCommonWordsTreeName() + UNDER_LINE +
                            v.getUserId(), soid);

                    Long surperSoid = mapSoid.get(v.getSurperCommonWordsTreeName() + UNDER_LINE +
                            v.getUserId());

                    kct = new KnwCommonWordsTree();
                    kct = setKnwCommonWordsTree(v, soid, surperSoid);
                    listKnwCommonWordsTree.add(kct);

                    if (StringUtils.isNotEmpty(v.getCompositeInstanceName())) {
                        kci = new KnwCompositeInstance();
                        kcis = new KnwCompositeInstanceShortcut();
                        knb = new KnwNarrativeBlock();
                        setKnwComposite(v, soid, kci, kcis, knb);

                        listKnwCompositeInstance.add(kci);
                        listKnwCompositeInstanceShortcut.add(kcis);
                        listKnwNarrativeBlock.add(knb);
                    }

                } else {
                    soid = mapSoid.get(v.getCommonWordsTreeName() + UNDER_LINE + v.getUserId());
                    if (StringUtils.isNotEmpty(v.getCompositeInstanceName())) {
                        kci = new KnwCompositeInstance();
                        kcis = new KnwCompositeInstanceShortcut();
                        knb = new KnwNarrativeBlock();
                        setKnwComposite(v, soid, kci, kcis, knb);

                        listKnwCompositeInstance.add(kci);
                        listKnwCompositeInstanceShortcut.add(kcis);
                        listKnwNarrativeBlock.add(knb);
                    }
                }
            }
        }

        vo.setListKnwCommonWordsTree(listKnwCommonWordsTree);
        vo.setListKnwCompositeInstance(listKnwCompositeInstance);
        vo.setListKnwCompositeInstanceShortcut(listKnwCompositeInstanceShortcut);
        vo.setListKnwNarrativeBlock(listKnwNarrativeBlock);
        result = knwCompositeInstanceApi.addKnwComposite(vo);
        return result;
    }

    /**
     * 设置树结构
     * @param v
     * @param soid
     * @return
     */
    private KnwCommonWordsTree setKnwCommonWordsTree(KnwCompositeInstanceExcelVo v,
                                                     Long soid, Long surperSoid) {
        KnwCommonWordsTree kct = new KnwCommonWordsTree();

        kct.setSurperCommonWordsTreeSoid(surperSoid);
        //常用语树形分类标识
        kct.setCommonWordsTreeSoid(soid);
        //常用语树形分类名称
        kct.setCommonWordsTreeName(v.getCommonWordsTreeName());
        //加五笔码和拼音码
        kct.setPyCode(CharTransFormUtil.toPinyinSimple(v.getCommonWordsTreeName()));
        kct.setWbCode(CharTransFormUtil.toWubi(v.getCommonWordsTreeName()));
        //149L启用
        kct.setStatus(STATUS);
        EmployeeInfoTmpVo eitv = mapEmployeeInfoVo.get(v.getUserId());
        if (eitv != null) {
            //创建人
            kct.setCreator(eitv.getEmployeeSoid());
            //组织标识
            kct.setOrgInfoSoid(eitv.getOrgInfoSoid());
            kct.setBusinessUnitSoid(eitv.getBusinessUnitSoid());
        }
        kct.setCreateDate(new Date());
        kct.setUpdateDate(new Date());
        kct.setIsDelete(0l);
        kct.setIsShare(new Short("0"));
        kct.setSerialNo(new Short("1"));
        return kct;
    }

    /**
     * 设置复合数据
     * @param v
     * @param commonWordsTreeSoid
     * @return
     */
    private void setKnwComposite(KnwCompositeInstanceExcelVo v,
                                 Long commonWordsTreeSoid,
                                 KnwCompositeInstance kci,
                                 KnwCompositeInstanceShortcut kcis,
                                 KnwNarrativeBlock knb) {
        // KnwCompositeInstance表设置
        Long compositeInstanceSoid = soidService.getSoid();
        kci.setCompositeInstanceSoid(compositeInstanceSoid);
        kci.setCommonWordsTreeSoid(commonWordsTreeSoid);
        if (StringUtils.isNotEmpty(v.getCompositeInstanceName())) {
            kci.setCompositeInstanceName(v.getCompositeInstanceName());
            kci.setPyCode(
                    CharTransFormUtil.toPinyinSimple(v.getCompositeInstanceName()));
            kci.setWbCode(
                    CharTransFormUtil.toWubi(v.getCompositeInstanceName()));
        }
        EmployeeInfoTmpVo eitv = mapEmployeeInfoVo.get(v.getUserId());
        if (eitv != null) {
            //创建人
            kci.setCreator(eitv.getEmployeeSoid());
            //组织标识
            kci.setOrgInfoSoid(eitv.getOrgInfoSoid());
            kci.setBusinessUnitSoid(eitv.getBusinessUnitSoid());
        }
        kci.setIsDelete(IS_DELETE);
        kci.setStatus(STATUS);
        kci.setCreateDate(new Date());

        // KnwCompositeInstanceShortcut表设置
        kcis.setCompositeInstanceSoid(compositeInstanceSoid);
        Long compositeInstanceShortcutSoid = soidService.getSoid();
        kcis.setCompositeInstanceShortcutSoid(compositeInstanceShortcutSoid);
        if (StringUtils.isNotEmpty(v.getCompositeInstanceName())) {
            kcis.setShortcut(
                    CharTransFormUtil.toPinyinSimple(v.getCompositeInstanceName()));
            kcis.setShortcutType(SHORTCUT_TYPE);
        }
        if (eitv != null) {
            //创建人
            kcis.setCreator(eitv.getEmployeeSoid());
        }
        kcis.setStatus(STATUS);
        kcis.setIsDelete(IS_DELETE);
        kcis.setCreateDate(new Date());

        // KnwNarrativeBlock表设置
        knb.setCompositeInstanceSoid(compositeInstanceSoid);
        knb.setNarrativeBlockSoid(soidService.getSoid());
        if (eitv != null) {
            //创建人
            knb.setCreate(eitv.getEmployeeSoid());
        }
        knb.setIsDelete(IS_DELETE);
        knb.setCreateDate(new Date());

        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isEmpty(v.getUsContent())){
            map.put("usContent", "");
        }else {
            map.put("usContent", v.getUsContent());
        }
        if (StringUtils.isEmpty(v.getUsDiagnosis())){
            map.put("usDiagnosis", "");
        }else {
            map.put("usDiagnosis", v.getUsDiagnosis());
        }
        JSONObject json = new JSONObject(map);
        knb.setNarrativeBlock(json.toString());
    }

    private File getFileTmp() {
        return fileTmp;
    }
}
